package com.example.demo.common.com.example.demo;


import com.amazonaws.services.dynamodbv2.xspec.S;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;

public class ServiceContext {

    public static void main(String[] args) {
        m1();

        System.out.println("==========================================");
        m2();

        System.out.println("==========================================");
        m3();

        System.out.println("==========================================");
        m4();
    }

    private static void m1() {
        ThreadLocal<String> threadLocal = new ThreadLocal<>();
        threadLocal.set("6666");

        Thread thread = new Thread(() -> {
            System.out.println(threadLocal.get());
        });
        thread.start();
    }

    private static void m2() {
        ThreadLocal<String> threadLocal = new ThreadLocal<>();
        threadLocal.set("6666");

        IntStream.range(1, 10).parallel().forEach(x -> {
            System.out.println(String.format("%s - %s", x, threadLocal.get()));
        });
    }

    private static void m3() {
        InheritableThreadLocal<String> inheritableThreadLocal = new InheritableThreadLocal<>();
        inheritableThreadLocal.set("11111111");

        Thread thread = new Thread(() -> {
            System.out.println(inheritableThreadLocal.get());
        });

        thread.start();

        IntStream.range(1, 5).boxed().forEach(x -> {
            System.out.println(String.format("%s - %s", x, inheritableThreadLocal.get()));
        });
    }

    private static void m4() {
        // 线程复用导致treadloaclmap值未变
        try {
            InheritableThreadLocal<String> inheritableThreadLocal = new InheritableThreadLocal<>();
            ExecutorService executorService = Executors.newFixedThreadPool(1);
            CountDownLatch cdl1 = new CountDownLatch(1);
            CountDownLatch cdl2 = new CountDownLatch(1);

            inheritableThreadLocal.set("main thread 1 ...");

            executorService.execute(() -> {
                System.out.println("thread1-" + inheritableThreadLocal.get());
                cdl1.countDown();
            });
            cdl1.await();
            System.out.println(inheritableThreadLocal.get());

            System.out.println("--------------------------------------------------");
            System.out.println("--------------------------------------------------");

            inheritableThreadLocal.set("main thread 2 ...");

            executorService.execute(() -> {
                System.out.println("thread2-" + inheritableThreadLocal.get());
                cdl2.countDown();
            });
            cdl2.await();
            System.out.println(inheritableThreadLocal.get());

            executorService.shutdown();

        } catch (Exception e) {
            // todo
        }
    }
}
